import { Component } from '@angular/core';
import { NavController,AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { SignService } from '../../providers/sign';

import * as moment from 'moment';

@Component({
	selector: 'page-signup',
	templateUrl: 'signup.html',
	providers: [SignService]
})
export class SignupPage {

	oId: string;
	loading: boolean;
	sequence: number;

	days: Array<{ day: number, dayOfweek: string, isSigned: boolean }> = []; // 存储所有天数
	today: number;

	month: string; // 中文月份
	offset: number;  // 滚动位置

	signText: string = '签到'; // 按钮文字
	signStatus: boolean = false; // 当天签到状态

	constructor(
		private navCtrl: NavController,
		private signService: SignService,
		private alertCtrl: AlertController,
		private storage: Storage
	) {
		moment.locale('zh-cn'); // 设置中文格式
		this.loading = true;
		this.sequence = 0;
		this.month = moment().format('MMMM'); // 获取月份用于中文显示
		this.today = moment().date();
	};

	ionViewWillEnter() {
		this.storage.get('openid').then(v => {
			this.oId = v;
			this.signService.getCheckInMonth(this.oId).then(result => {
				// 获取本月签到状态
				this.loading = false;
				this.isCheckIn(result.currentdate_checkined);
				this.sequence = result.week_checkined;

				let	dayOfMonth = result.month_checkined;
				let	length: number = dayOfMonth.length;
				let w: string;
				let	i = 1;

				for (; i <= length; i++) {
					w = moment(dayOfMonth[i - 1].checkin_date).format('ddd');
					this.days.push({ day: i, dayOfweek: w, isSigned: dayOfMonth[i - 1].is_checkin })
				}
				this.offset = (this.today - 1) * 40; // 设置滚动到当天
			})
		})
	};

	// 签到
	sign() {
		if(this.signStatus === false){
			this.signService.checkIn(this.oId).then(result => {
				if (result === '10000') {
					this.isCheckIn(true);
					this.sequence++;
					this.days[this.today - 1].isSigned = true;
				}
			});
		}else{
			let alert = this.alertCtrl.create({
				title: '您已成功签到',
				buttons: ['确定']
			});
			alert.present();
		}
	};

	// 设置是否签到
	isCheckIn(statu){
		if(statu){
			this.signText = '已签到';
			this.signStatus = true;
		}else{
			this.signText = '签到';
			this.signStatus = false;
		}
	}
}
